package com.ruoyi.system.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
@PropertySource({"classpath:application.properties"})
public class OssServiceImpl {

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.bucketName}")
    private String bucketName;

    @Value("${oss.path}")
    private String path;

    /**
     * 上传文件到OSS（阿里云对象存储服务）
     *
     * @param file 需要上传的文件，类型为MultipartFile
     * @return 上传成功后返回文件的URL
     * @throws IOException 如果上传过程中发生IO异常
     */
    public String uploadImageToOSS(MultipartFile file) throws IOException {
        // 生成唯一的文件名，加上原始文件名
        String fileName = UUID.randomUUID().toString() + file.getOriginalFilename();
        // 创建OSS客户端实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 将文件流上传到指定的存储桶内
            ossClient.putObject(bucketName, path + fileName, file.getInputStream());
            // 返回文件的URL
            return "https://" + bucketName + "." + endpoint + "/" + path + fileName;
        } finally {
            // 无论上传成功与否，最后都关闭OSS客户端
            ossClient.shutdown();
        }
    }
}
